package com.ttn.user.bus;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.ttn.entities.User;

@Service
public class UserService extends HibernateDaoSupport implements
		org.springframework.security.core.userdetails.UserDetailsService {

	public User createEmptyUser(UsernamePasswordAuthenticationToken currentUser) {
		
			return new User();
		
		
	}

	public void saveUser(User user) throws Exception {
		Md5PasswordEncoder md = new Md5PasswordEncoder();
		String password = md.encodePassword(user.getPassword(), null);
		user.setPassword(password);
		this.getHibernateTemplate().save(user);		
	}

	public List<User> getUserByLogin(String login) {
		List<User> users = this.getHibernateTemplate().find(
				" select u from User u where u.login = ?", login);
		return users;
	}

	@Autowired
	public void init(SessionFactory factory) {
		setSessionFactory(factory);
	}

	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException, DataAccessException {

		List<User> users = this.getHibernateTemplate().find(
				" select u from User u where u.login = ?", arg0);
		if (users.isEmpty()) {
			throw new UsernameNotFoundException(arg0);
		}
		return users.get(0);		
	}

}
